﻿using Frogsoft.Data;
using Frogsoft.Domain.Permission;
using Frogsoft.Permission.Dtos;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Frogsoft.Permission
{

    public class ProfileService
    {
        private readonly UserManager<AppUser>? _userManager;
        private readonly RoleManager<IdentityRole>? _roleManager;

        public ProfileService(UserManager<AppUser>? userManager, RoleManager<IdentityRole>? roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }

        public UserInfoDto GetUserInfo(string userName)
        {
            List<string> permissions;
            var user = _userManager.FindByNameAsync(userName).Result;
            var roles = _userManager.GetRolesAsync(user).Result;
            List<Claim> roleList = new List<Claim>();
            foreach (var roleStr in roles)
            {
                var _role = _roleManager.FindByNameAsync(roleStr).Result;
                roleList.AddRange(_roleManager.GetClaimsAsync(_role).Result);
            }
            var query = from p in roleList select p.Type;
            permissions = query.Distinct().ToList();
            UserInfoDto userInfo = new UserInfoDto(userName, permissions);
            return userInfo;
        }

    }
}
